<?php
if ( ! function_exists('ipaccess'))
{
 	function ipaccess()
	{
	
		$allow= array(
			"127.0.0.1/0",
			"192.168.4.0/255",
			"192.168.5.0/255",
		);

		$CI = & get_instance();
		$lip = ip2long($CI->input->ip_address());
		$isallow = false;
		foreach($allow as $val)
		{
			$part = explode('/',$val);
			if($lip>=ip2long($part[0]) and $lip<=ip2long($part[0])+ intval($part[1]))
			{
				$isallow = true;
				break;
			}
		}		
		//echo "isallow:",long2ip($lip),",$isallow";
		return $isallow;
	}
}

if ( ! function_exists('translate'))
{
	function translate($query)
	{
		$debug = false;
		$url = "https://www.googleapis.com/language/translate/v2";
		$values = array(
		               'key'    => "AIzaSyAAYa3XqLYsRyRrT5HGqWU8fiu5szZlKVk",
		               'source' => "zh-CN",
		               'target' => "en",
		               'q'      => $query
		           );
		
		//这里注意php.ini的配置参数arg_separator.output，需要设置为&
		$formData = http_build_query($values);
		/*
		$key = "AIzaSyAAYa3XqLYsRyRrT5HGqWU8fiu5szZlKVk";
		$source = "zh-CN";
		$target = "en";
		//$formData = "key=$key&source=$source&target=$target&q=$query";
		echo $formData;
		*/
		/*
		$url .= "?".$formData;
		//echo $url;
		echo file_get_contents($url);
		*/
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; MSIE 7.0; Windows NT 6.0; en-US)');
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $formData);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: GET'));
		
		$body = curl_exec($ch);
		
		curl_close($ch);
		$ret = '';
		$data = json_decode($body, true);
		if($debug)	print_r($data);
	/*	
	  if (!is_array($data) || !array_key_exists('data', $data)) {
	      throw new Exception('Unable to find data key');
	  }	
	  if (!array_key_exists('translations', $data['data'])) {
	      throw new Exception('Unable to find translations key');
	  }
		if (!is_array($data['data']['translations'])) {
		    throw new Exception('Expected array for translations');
		}
	*/	
	if(!empty($data))
		foreach ($data['data']['translations'] as $translation) {
			if(!empty($translation['translatedText']))
		    $ret =  $translation['translatedText'];
		}	
	  return $ret;
	}
	
}
?>
